import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../../services/api_service.dart';
import '../../services/auth_service.dart';
import 'package:provider/provider.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';

class PutawayDetailScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;

  const PutawayDetailScreen({super.key, required this.jsonData});

  @override
  _PutawayDetailScreenState createState() => _PutawayDetailScreenState();
}

class _PutawayDetailScreenState extends State<PutawayDetailScreen> {
  int? selectedIndex; // 选中的索引
  List<Map<String, dynamic>> availableLpns = []; // 动态LPN列表
  String currentTask = ''; // 当前任务显示
  String? lpnValue = ''; // LPN值
  String itemValue = ''; // 物料值
  String quantityValue = ''; // 数量值
  String locationValue = ''; // 位置值
  late int? warehouseId;
  late int? loadId;
  late String? loadNumber;
  bool _isLoading = false;

  // 字体缩放因子
  late double _fontScale;
  // 间距缩放因子
  late double _spacingScale;
  late double labelFontSize = 13;
  late double textFontSize = 12; // 对应Search的listFontSize
  late double errorFontSize = 13;
  late double buttonFontSize = 15;

  @override
  void initState() {
    super.initState();
    loadNumber = widget.jsonData['loadNumber'];
    loadId = widget.jsonData['loadId'];
    _init();
    
    WidgetsBinding.instance.addPostFrameCallback((_) {
    });
  }

  Future<void> _init() async{
    final authService = Provider.of<AuthService>(context, listen: false);
    final user = authService.currentUser;
    warehouseId = user?.warehouse;
    final jsondata = await _fetchPutawayDetailData(loadId);
    _parseJsonData(jsondata);
  }

  // 调用接口获取渲染putaway detail页面的数据
  Future<Map<dynamic,dynamic>> _fetchPutawayDetailData(int? id) async{
    final apiUrl = ApiService.baseURL + ApiService.fetchPutawayDetail;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      print('url---:$apiUrl$id');
      final response = await http.get(
        Uri.parse('$apiUrl$id'),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData---:${jsonData}');
        if (jsonData['code'] == 2000) {
          return jsonData;
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
  }

  // 解析JSON数据并初始化列表（原逻辑不变）
  void _parseJsonData(Map<dynamic, dynamic> data) {
    final dataList = data['data'] as List<dynamic>;
    setState(() {
      availableLpns = dataList.map((item) {
        return {
          'id': item['id'],
          'lpn': item['shipment_line']['lpn_number'] ?? 'N/A',
          'item': item['item_number'],
          'location': item['location'],
          'quantity': item['quantity'],
          'pack_type': item['pack_type'],
          'status': item['status'],
        };
      }).toList();
    });
  }

  // 更新选择逻辑（原逻辑不变）
  void _updateSelectedItem(int index) {
    if (index < 0 || index >= availableLpns.length) return;
    
    // 如果点击已选中的项，则取消选中
    if (selectedIndex == index) {
      setState(() {
        selectedIndex = null;
        lpnValue = '';
        itemValue = '';
        quantityValue = '';
        locationValue = '';
        currentTask = '';
      });
      return;
    }
    
    // 否则选中该项
    final selectedItem = availableLpns[index];
    setState(() {
      selectedIndex = index;
      currentTask = '${index + 1}/${availableLpns.length}';
      lpnValue = selectedItem['lpn'] ?? 'N/A';
      itemValue = selectedItem['item'] ?? 'N/A';
      quantityValue = '${selectedItem['quantity']}(${selectedItem['pack_type']})';
      locationValue = selectedItem['location'];
    });
  }

  // Rollback API调用（原逻辑不变）
  Future<void> _callRollbackApi() async {
    if (selectedIndex == null) return;
    
    final item = availableLpns[selectedIndex!];
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    final apiUrl = ApiService.baseURL + ApiService.rollbackPutaway;
    final url = Uri.parse(apiUrl);

    setState(() => _isLoading = true);
    try {
      var requestBody = {
        'task_id': item['id']
      };
      final response = await http.post(
        url,
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
        body: jsonEncode(requestBody),
      );

      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('url---$url');
        print('jsonData---$jsonData');
        
        if (jsonData['code'] == 2000) {
          
          MessageBox.showMessageBox(context, jsonData['msg'], isError: false);
          setState(() {
            availableLpns.removeAt(selectedIndex!);
            
            // 重置选择状态
            selectedIndex = null;
            lpnValue = '';
            itemValue = '';
            quantityValue = '';
            locationValue = '';
            currentTask = '';
          });
        } else {
          MessageBox.showMessageBox(context, jsonData['msg'], isError: true);
        }
      } else {
        MessageBox.showMessageBox(context, response.statusCode, isError: true);
      }
    } catch (e) {
      MessageBox.showMessageBox(context, e, isError: true);
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // Finish API调用（原逻辑不变）
  Future<void> _callFinishApi() async {
    if (availableLpns.isEmpty) {
      MessageBox.showMessageBox(context, 'No data found.', isError: true);
      return;
    }

    final url = Uri.parse(ApiService.baseURL + ApiService.finishPutaway);
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    final requestBody = {
      "load":loadId,
      "task_ids": availableLpns.map((item) => item['id']).toList()
    };
    
    try {
      print('requestBody----${requestBody}');
      print('url----${url}');
      final response = await http.post(
        url,
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
        body: jsonEncode(requestBody),
      );

      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData----${jsonData}');
        
        if (jsonData['code'] == 2000) {
          await showDialog(
            context: context,
            barrierDismissible: false, // 用户必须点击按钮才能关闭
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(
                  'Success',
                  style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18 * _fontScale, color:Color.fromARGB(255, 4, 170, 10)),
                ),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Text(jsonData['msg']), // 显示纯净的错误信息
                    ],
                  ),
                ),
                actions: <Widget>[
                  TextButton(
                    child: const Text('OK'),
                    onPressed: () {
                      Navigator.of(context).pop(); // 关闭弹窗
                    },
                  ),
                ],
              );
            },
          );
          setState(() => _isLoading = true);
          Navigator.pushNamed(
            context,
            '/inbound/putaway',
          );
        } else {
          MessageBox.showMessageBox(context, jsonData['msg'], isError: true);
        }
      } else {
        MessageBox.showMessageBox(context, response.statusCode, isError: true);
      }
    } catch (e) {
      MessageBox.showMessageBox(context, e, isError: true);
    } finally {
      setState(() => _isLoading = false);
    }
  }

  // 构建信息行（原逻辑不变）
  Widget _buildInfoRow(String label, String? value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4 * _spacingScale),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: labelFontSize * _fontScale
              ),
            ),
          ),
          Expanded(
            child: Text(
              value.toString(),
              style: TextStyle(
                fontSize: textFontSize * _fontScale,
                color: Colors.black87
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    _spacingScale = _fontScale;
    
    return Scaffold(
      appBar: AppBar(
        title: Text('Putaway Detail', style: TextStyle(fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            // 返回PutawayTasksScreen并传递参数
            Navigator.pushNamed(
              context,
              '/inbound/putaway-tasks',
              arguments: {
                'loadNumber':loadNumber,
                'loadId':loadId
              },
            );
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363)
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Padding(
              padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 可用LPN标题（保持原文本，调整字体缩放）
                  Text(
                    'LPN Details:',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: labelFontSize * _fontScale
                    ),
                  ),
                  SizedBox(height: 10 * _spacingScale),
                  
                  // ------------- 核心修改：列表样式对齐SearchDetaiScreen -------------
                  Expanded(
                    child: Container(
                      // 列表外层容器样式：与Search一致的边框、圆角
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey, width: 1.0),
                        borderRadius: BorderRadius.circular(4.0),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(4.0),
                        child: ListView.builder(
                          physics: const ClampingScrollPhysics(),
                          itemCount: availableLpns.length,
                          itemBuilder: (context, index) {
                            final item = availableLpns[index];
                            final isSelected = selectedIndex == index; // 保留原选中逻辑
                            
                            // 列表项改为卡片式：与Search一致的间距、边框、背景
                            return InkWell(
                              onTap: () => _updateSelectedItem(index), // 保留原点击逻辑
                              child: Container(
                                margin: const EdgeInsets.symmetric(vertical: 2), // 卡片垂直间距
                                decoration: BoxDecoration(
                                  border: Border.all(color: const Color.fromARGB(255, 169, 168, 168), width: 0.5),
                                  borderRadius: BorderRadius.circular(4.0),
                                  color: isSelected ? Colors.green[50] : null, // 选中背景色
                                ),
                                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), // 卡片内边距
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          item['item'] ?? 'N/A',
                                          style: TextStyle(
                                            fontSize: textFontSize * _fontScale,
                                            fontWeight: FontWeight.bold,
                                            color: isSelected ? Colors.green : Colors.black,
                                          ),
                                        ),
                                        Expanded(
                                          child: Padding(
                                            padding: const EdgeInsets.only(left: 12),
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              children: [
                                                Text('Status: ', style: TextStyle(
                                                  fontSize: textFontSize * _fontScale,
                                                  color: isSelected ? Colors.green : Colors.black87,
                                                ),),
                                                Text(
                                                  '${item['status'] ?? 'N/A'}',
                                                  style: TextStyle(
                                                    fontSize: textFontSize * _fontScale,
                                                    color: isSelected ? Colors.green : Colors.black87,
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    SizedBox(height: 6 * _spacingScale),
                                    
                                    // 底部横排字段：Item/Location/Quantity/Status（与Search的多字段横排一致）
                                    Row(
                                      children: [
                                        // Item字段
                                        Expanded(
                                          flex: 1,
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Text(
                                                'LPN Number: ',
                                                style: TextStyle(
                                                  fontSize: textFontSize * _fontScale,
                                                  color: isSelected ? Colors.green : Colors.black87,
                                                ),
                                              ),
                                              Text(
                                                '${item['lpn'] ?? 'N/A'}',
                                                style: TextStyle(
                                                  fontSize: textFontSize * _fontScale,
                                                  color: isSelected ? Colors.green : Colors.black87,
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                        
                                        // Location字段
                                        Expanded(
                                          flex: 1,
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Text(
                                                'Location: ',
                                                style: TextStyle(
                                                  fontSize: textFontSize * _fontScale,
                                                  color: isSelected ? Colors.green : Colors.black87,
                                                ),
                                              ),
                                              Text(
                                                '${item['location'] ?? 'N/A'}',
                                                style: TextStyle(
                                                  fontSize: textFontSize * _fontScale,
                                                  color: isSelected ? Colors.green : Colors.black87,
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                        
                                        // Quantity字段（含PackType）
                                        Expanded(
                                          flex: 1,
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Text(
                                                'Qty: ',
                                                style: TextStyle(
                                                  fontSize: textFontSize * _fontScale,
                                                  color: isSelected ? Colors.green : Colors.black87,
                                                ),
                                              ),
                                              Text(
                                                '${item['quantity']}(${item['pack_type']})',
                                                style: TextStyle(
                                                  fontSize: textFontSize * _fontScale,
                                                  color: isSelected ? Colors.green : Colors.black87,
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                  ),
                  // ------------- 列表样式修改结束 -------------
                  
                  // 任务信息行（原逻辑不变）
                  _buildInfoRow('Tasks:', currentTask),
                  _buildInfoRow('LPN:', lpnValue),
                  _buildInfoRow('Item:', itemValue),
                  _buildInfoRow('Quantity:', quantityValue),
                  _buildInfoRow('Location:', locationValue),
                  
                  SizedBox(height: 15 * _spacingScale),
                  
                  // 按钮区域（原逻辑不变）
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text(
                        'Finish', 
                        style: TextStyle(
                          fontWeight: FontWeight.bold, 
                          fontSize: buttonFontSize * _fontScale, 
                          color: Colors.white
                        )
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF008363),
                        padding: EdgeInsets.symmetric(vertical: 1 * _spacingScale),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                      ),
                      onPressed: _callFinishApi,
                    ),
                  ),
                  SizedBox(height: 8 * _spacingScale),
                  
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text(
                        'Rollback', 
                        style: TextStyle(
                          fontWeight: FontWeight.bold, 
                          fontSize: buttonFontSize * _fontScale, 
                          color: Colors.white
                        )
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF008363),
                        padding: EdgeInsets.symmetric(vertical: 1 * _spacingScale),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                      ),
                      onPressed: () {
                        if (selectedIndex != null) {
                          _callRollbackApi();
                        } else {
                          MessageBox.showMessageBox(context, 'No selected task.', isError: true);
                        }
                      },
                    ),
                  ),
                  SizedBox(height: 8 * _spacingScale),
                  
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text(
                        'Exception',
                        style: TextStyle(
                          fontWeight: FontWeight.bold, 
                          fontSize: buttonFontSize * _fontScale, 
                          color: Colors.white
                        )
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        padding: EdgeInsets.symmetric(vertical: 1 * _spacingScale),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                      ),
                      onPressed: () {
                        // MessageBox.showMessageBox(context, 'The functions need to be improved.', isError: true);
                      },
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}